package middleware

import (
	"github.com/gin-gonic/gin"
	"learningProject/vueGoProject/common"
	"learningProject/vueGoProject/model"
	"net/http"
	"strings"
)

// 中间件
func AuthMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取 authorization header
		tokenString := c.GetHeader("Authorization")

		// 验证参数
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer") {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token参数错误！",
			})
			c.Abort()
			return
		}

		tokenString = tokenString[7:] // 因为Bearer占了7个字节，所以读取第7位后程度真正数据
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token校验错误！",
			})
			c.Abort()
			return
		}

		// 验证通过后获取token中的信息
		userId := claims.UserId
		var user model.User
		common.DB.First(&user, userId) // 根据id查找数据

		if user.ID == 0 { // 数据库没有userId所对应的数据
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": 401,
				"msg":  "token校验错误，用户不存在！",
			})
			c.Abort()
			return
		}

		// 用户存在，将user信息写入上下文
		c.Set("user", user)
		c.Next()
	}
}
